<template>
  <view class="page">
    <view class="header c-font-s1">
      <u-search placeholder="请输入"
                v-model="keywords"
                bgColor="#fff"
                :show-action="false"
                height="90"
                color="#000"
                margin="20rpx 20rpx"
                clearable
                search-icon-color="#666"
                @change="handleSearch"
                @clear="handleClear"></u-search>
      <view class="header-wrapper u-border-bottom">
        <u-tabs :list="tabs"
                :current="current"
                :is-scroll="false"
                lineColor="#307DCD"
                height="90"
                font-size="32rpx"
                :active-item-style="tabItemActiveStyle"
                :inactive-item-style="tabItemInactiveStyle"
                @change="handleToggleTabs"></u-tabs>
      </view>
    </view>
    <view class="content">
      <view class="list">
        <view class="list-item c-color-u4 c-font-s2 u-border-bottom"
              v-for="item in list"
              :key="item.id"
              @click="handleChecked(item)">{{ item.storeName }}</view>
      </view>
    </view>
    <u-toast ref="uToast"></u-toast>
  </view>
</template>

<script>
import {
  getNearByStores,
  getStoreList,
  wxGetTxMapByLatLng
} from '../../common/service'
export default {
  data() {
    return {
      keywords: '',
      current: 0,
      tabs: [{ name: '自营' }, { name: '加盟' }, { name: '装饰' }],
      tabItemActiveStyle: {
        color: "#307DCD",
        fontWeight: "bold",
        fontSize: '32rpx'
      },
      tabItemInactiveStyle: {
        color: "#999999",
        fontWeight: "500",
        fontSize: '32rpx'
      },
      list: [],
      latitude: '',
      longitude: '',
      province: '',
      city: '',
    }
  },
  methods: {
    handleToggleTabs(index) {
      this.current = index
      this.list = []
      this.handleSearch(this.keywords)
    },
    handleSearch(val) {
      this.$u.debounce(this.queryStoreList, 300)
    },
    handleClear() {
      this.keywords = ''
      this.list = []
    },
    handleChecked(item) {
      // let pages = getCurrentPages()
      // let prevPage = pages[pages.length - 2]
      // uni.navigateBack({
      //   delta: 1,
      //   success: () => {
      //     prevPage.$vm.emitDataFunc(item)
      //   }
      // })
      this.emitDataFunc(item)
    },
    async queryStoreList() {
      const params = {
        code: this.CONFIG.user?.id || '',
        storeName: this.keywords,
        searchType: this.current + 1
      }
      this.keywords && getStoreList(params, res => {
        res.data && res.data.code === 200 ? (
          this.$nextTick(() => {
            this.list = res.data.data
          })
        ) : (
          this.$refs.uToast.show({
            title: res.data.msg || '数据请求出错',
            type: 'error',
            duration: 2000
          })
        )
      })
    },
    getLocInfo() {
      wxGetTxMapByLatLng({ "lat": this.latitude, "lng": this.longitude }, (res) => {
        if (res.data.status == '00000') {
          let result = res.data.data.result
          const province = result.address_component.province
          const city = result.address_component.city
          this.province = province
          this.city = city
          // 根据经纬度 省/市
          this.getNearLocation()
        } else {
          uni.showToast({
            message: res.data.message,
            duration: 2000,
            icon: 'error'
          })
        }
      })
    },
    getNearLocation() {
      const params = {
        province: this.province || '',
        city: this.city || '',
        latitude: this.latitude || '',
        longitude: this.longitude || ''
      }
      getNearByStores(params, res => {
        if (res.statusCode == 200) {
          const rs = res.data
          if (rs && rs.code == 200) {
            const pointsListRes = rs.data || []
            this.list = []
            if (pointsListRes) {
              for (const item in pointsListRes) {
                const obj = pointsListRes[item]
                obj.RANGE = item
                this.list.push(obj)
              }
            }
          } else {
            this.$refs.uToast.show({
              title: rs.msg || '没有查询到定位附近的门店，请手动选择',
              type: 'error',
              duration: 3000,
              callback: function () {
                return
              }
            })
          }
        }
      })
    },
    emitDataFunc(item) {
      // 门店定位地址
      if (item.latitude && item.longitude) {
        // 定位地址和门店地址距离计算
        const distance = this.getGreatCircleDistance(this.latitude * 1, this.longitude * 1, item.latitude * 1, item.longitude * 1)
        let isTest = location.href.indexOf('webtest') > -1
        if (distance > 0.5 && !isTest) {
          this.$refs.uToast.show({
            title: '该店面地址不在打卡范围内，请确认打卡位置或手机定位是否开启' + '当前：' + this.latitude + ',' + this.longitude + '店面：' + item.latitude + ',' + item.longitude,
            type: 'error',
            duration: 3000,
            callback: function () {
              return
            }
          })
        } else {
          uni.navigateTo({
            url: `../toStoreDetail/index?id=${item.id}`
          })
        }

      } else {
        this.$refs.uToast.show({
          title: '该店面地址为空，先到图像采集维护店面地址再进行助店打卡',
          type: 'error',
          duration: 3000,
          callback: function () {
            return
          }
        })
      }
    },
    getGreatCircleDistance(lat1, lon1, lat2, lon2) {
      const radians = Math.PI / 180
      const R = 6371 // 地球半径，单位为公里

      const deltaLat = (lat2 - lat1) * radians
      const deltaLon = (lon2 - lon1) * radians

      lat1 = lat1 * radians
      lat2 = lat2 * radians

      const sinThreshold = Math.sin(deltaLat / 2) * Math.sin(deltaLat / 2) +
        Math.cos(lat1) * Math.cos(lat2) *
        Math.sin(deltaLon / 2) * Math.sin(deltaLon / 2)
      const angle = 2 * Math.atan2(Math.sqrt(sinThreshold), Math.sqrt(1 - sinThreshold))
      return angle * R
    },
  },
  onLoad(opt) {
    this.LOGINACTION()
    // 获取用户当前定位
    this.INITWXJSDK(this.CONFIG.appid, location.origin + location.pathname + location.search, () => {
      this.$wx.getLocation({
        type: 'gcj02',
        success: res => {
          this.latitude = res.latitude
          this.longitude = res.longitude
          this.getLocation()
        },
        cancel: err => {
          alert('用户拒绝授权获取地理位置！')
        }
      })
    }, ['getLocation'])
  }
}
</script>

<style lang="scss" scoped>
// uni-page-body {
//   background: #f8f8f8;
//   min-height: 100%;
//   -ms-overflow-style: none;
//   scrollbar-width: none;
//   &::-webkit-scrollbar {
//     display: none;
//   }
// }
// 字体文件颜色汇总
$colors: (
  'u1': #333,
  'u2': #666,
  'u3': #999,
  'u4': #307dcd,
  'u5': #f3f5f7,
);
$fonts: (
  's1': 28rpx,
  's2': 30rpx,
  's3': 32rpx,
);
@each $key, $val in $colors {
  .c-color-#{$key} {
    color: $val;
  }
}
@each $key, $val in $fonts {
  .c-font-#{$key} {
    font-size: $val;
  }
}
uni-page-body {
  background: #fff;
  min-height: 100%;
}
.header {
  position: fixed;
  top: 0;
  left: 0;
  right: 0;
  background: #f3f5f7;
  z-index: 9;
  display: flex;
  flex-direction: column;
}
.content {
  background: #fff;
  padding-top: 220rpx;
}
.list {
  background: #fff;
  // 关联滚动，缺少无法滚动
  max-height: calc(100vh - 220rpx);
  overflow: hidden auto;
  &-item {
    height: 110rpx;
    display: flex;
    align-items: center;
    padding-left: 30rpx;
    box-sizing: border-box;
  }
}
</style>
